package com.peace.hospital.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.peace.hospital.entity.User;
import com.peace.hospital.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Timestamp;
import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xie
 * @since 2019-10-12
 */
@RestController
@RequestMapping("/user")
public class UserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
@Autowired
    private IUserService iUserService;

@Autowired
    private RedisTemplate redisTemplate;
    /**
     * 注册生成验证码，发送短信,并查询账户是否存在*/
//sendMessage(telephoneNumber)
@RequestMapping(value = "/register/{phone}",method = RequestMethod.GET)
    public String createVerifycode(@PathVariable("phone") String telephoneNumber) {
    User one = iUserService.getOne(new QueryWrapper<User>().eq("username", telephoneNumber));
    if(one==null) {
        System.out.println(telephoneNumber);
        return JSON.toJSONString(123456);
    }else
        return JSON.toJSONString(false);
    }

    /**用户注册*/
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public String userRegister(@RequestBody User user) {
        user.setUsername(user.getPhone());
        user.setRegistertime(LocalDateTime.now());
            boolean save = iUserService.save(user);
            return JSON.toJSONString(save);
    }

    /**用户密码账户登录*/
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String userLogin(@RequestBody User user) {
        User one = iUserService.getOne(new QueryWrapper<User>().eq("username",user.getUsername()).eq("upassword", user.getUpassword()));
        //获取Redis中的数据集合
        ValueOperations<String,String> operations = redisTemplate.opsForValue();
        operations.set("user",JSON.toJSONString(one));
        return JSON.toJSONString(one);
    }

    /**查询用户详情*/
    @RequestMapping(value = "/details/{uid}",method = RequestMethod.GET)
    public String getUserMessage(@PathVariable("uid") int uid) {
        //获取Redis中的数据集合
//        ValueOperations<String, String> operations = redisTemplate.opsForValue();
//        //获取指定的key值是否存在
//        boolean hasKey = redisTemplate.hasKey("user");
//        //如果存在则输出并将它删除，如果不存在则添加一个新的内容
//        if (hasKey) {
//            String info = operations.get("user");
//            System.out.println("现在的值: " + info + ", 查看完毕则删除! ! ! ! ");
//            return JSON.toJSONString(true);
//        } else {
//            System.out.println("没有数据则添加一个新的! !");
//            //   operations.set("user","当前时间:"+new Timestamp(System.currentTimeMillis()));
//            return JSON.toJSONString(false);
//        }
        User one = iUserService.getOne(new QueryWrapper<User>().eq("uid",uid));
        return JSON.toJSONStringWithDateFormat(one,"yyyy-MM-dd hh:mm:ss", SerializerFeature.WriteDateUseDateFormat);
    }


    /**用户头像上传*/
    @RequestMapping(value = "/details",method = RequestMethod.POST)
    public String userUpload(@RequestBody MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        String fileName = file.getOriginalFilename();
        String filePath = request.getServletContext().getRealPath("/update/");
        File dest = new File(filePath + fileName);
        if(!dest.exists()) {
            dest.mkdirs();
        }
        try {
            file.transferTo(dest);
            LOGGER.info("上传成功");
            ValueOperations<String,String> operations = redisTemplate.opsForValue();

            User user = JSONObject.parseObject(operations.get("user"), User.class);
            user.setPetname(filePath + fileName);
         operations.set("user",JSON.toJSONString(user));
            return "上传成功";
        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
        return "上传失败！";
    }
}
